package com.yuntianshi.service.impl;

import com.yuntianshi.common.MessageContant;
import com.yuntianshi.common.PageResult;
import com.yuntianshi.common.Result;
import com.yuntianshi.dao.MemberDao;
import com.yuntianshi.dao.OrderDao;
import com.yuntianshi.dao.OrderSettingDao;
import com.yuntianshi.dao.SetmealDao;
import com.yuntianshi.service.OrderService;
import com.yuntianshi.utils.DateUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yuntianshi.pojo.Member;
import com.yuntianshi.pojo.Order;
import com.yuntianshi.pojo.OrderSetting;
import com.yuntianshi.pojo.Setmeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 体检预约服务
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private SetmealDao setmealDao;

    //服务预约
    public Result order(Map map) throws Exception {
        //检查当前日期是否进行了预约设置
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if(orderSetting == null){
            return new Result(false, MessageContant.SELECTED_DATE_CANNOT_ORDER);
        }

        //检查预约日期是否预约已满
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if(reservations >= number){
            //预约已满，不能预约
            return new Result(false,MessageContant.ORDER_FULL);
        }

        //获取当前会员信息
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        //防止重复预约
        if(member != null){
            Integer memberId = member.getId();
            int setmealId = Integer.parseInt((String) map.get("setmealId"));
            String orderAddress = (String) map.get("orderAddress");
            Order order = new Order(memberId,date,null,"未开始",setmealId,orderAddress);
            List<Order> list = orderDao.findByCondition(order);
            if(list != null && list.size() > 0){
                //已经完成了预约，不能重复预约
                return new Result(false,MessageContant.HAS_ORDERED);
            }
        }

        //可以预约，设置预约人数加一
        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        if(member == null){
            //当前用户不是会员，需要添加到会员表
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            member.setFileNumber(telephone);
            memberDao.add(member);
        }

        Setmeal setmeal = setmealDao.findById(Integer.parseInt(map.get("setmealId").toString()));

        //保存预约信息到预约表
        Order order = new Order(member.getId(),
                date,
                (String)map.get("orderType"),
                Order.ORDERSTATUS_NO,
                Integer.parseInt((String) map.get("setmealId")),
                (String) map.get("orderAddress"));
        order.setSetmealName(setmeal.getName());
        order.setPhoneNumber((String) map.get("telephone"));
        order.setMemberName((String) map.get("name"));
        orderDao.add(order);

        return new Result(true,MessageContant.ORDER_SUCCESS,order.getId());
    }

    //根据id查询预约信息，包括体检人信息、套餐信息
    public Order findById(Integer id) throws Exception {
        Order order = orderDao.findById(id);
        String orderDateString = DateUtils.parseDate2String(order.getOrderDate());
        order.setOrderDateString(orderDateString);
        return order;
    }

    //分页查询
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) throws Exception{
        //        完成分页查询，基于MyBatis框架提供的分页助手插件完成
        if (queryString!=null&&queryString.length()>0){
            PageHelper.startPage(1,pageSize);
        }
        PageHelper.startPage(currentPage,pageSize);
        Page<Order> page = orderDao.selectByCondition(queryString);
        for (Order order : page) {
            order.setOrderDateString(DateUtils.parseDate2String(order.getOrderDate()));
        }
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Result add(Map map, Integer[] setmealIds) throws Exception{
        //检查当前日期是否进行了预约设置
        String orderDate = (String) map.get("orderDate");
        try {
            Date date = DateUtils.parseString2Date(orderDate);
        }catch (Exception e){
            return new Result(false,"日期格式错误");
        }
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if(orderSetting == null){
            return new Result(false, MessageContant.SELECTED_DATE_CANNOT_ORDER);
        }
        //检查预约日期是否预约已满
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if(reservations >= number){
            //预约已满，不能预约
            return new Result(false,MessageContant.ORDER_FULL);
        }
        //根据手机号进行查找会员，判断当前会员是否注册
        Member memberByPhoneNumber = memberDao.findByTelephone((String) map.get("phoneNumber"));
        //防止重复预约
        for (Integer setmealId : setmealIds) {
            if(memberByPhoneNumber != null){
                Integer memberId = memberByPhoneNumber.getId();
                String orderAddress = (String) map.get("orderAddress");
                Order order = new Order(memberId,date,null,"未开始",setmealId,orderAddress);
                List<Order> list = orderDao.findByCondition(order);
                if(list != null && list.size() > 0){
                    //已经完成了预约，不能重复预约
                    return new Result(false,MessageContant.HAS_ORDERED);
                }
            }
        }
        //可以预约，设置预约人数加一
        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        if (memberByPhoneNumber==null){
            //该会员未注册
            Member member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber((String) map.get("phoneNumber"));
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setEmail((String) map.get("email"));
            member.setRegTime(new Date());
            member.setFileNumber((String) map.get("phoneNumber"));
            memberDao.add(member);
        }
        Member memberByPhoneNumber2 = memberDao.findByTelephone((String) map.get("phoneNumber"));
        //该会员已注册
        for (Integer setmealId : setmealIds) {
            Setmeal setmealById = setmealDao.findById(setmealId);
            Order order = new Order();
            order.setMemberId(memberByPhoneNumber2.getId());
            order.setMemberName(memberByPhoneNumber2.getName());
            order.setPhoneNumber(memberByPhoneNumber2.getPhoneNumber());
            order.setOrderDate(date);
            order.setOrderType((String) map.get("orderType"));
            order.setOrderStatus((String) map.get("orderStatus"));
            order.setSetmealId(setmealById.getId());
            order.setSetmealName(setmealById.getName());
            order.setOrderAddress((String) map.get("orderAddress"));
            orderDao.add(order);
        }
        return new Result(true,MessageContant.ADD_ORDER_SUCCESS);
    }

    @Override
    public Result statusUpdate(Integer id) {
        //根据id获取对应订单信息
        Order order = orderDao.findById(id);
        //判断订单状态
        if (!(order!=null&&"未开始".equals(order.getOrderStatus()))){
            return new Result(false,"修改失败，未找到订单或订单已开始、已结束");
        }
        try {
            String orderStatus=Order.ORDERSTATUS_YES;
            order.setOrderStatus(orderStatus);
            orderDao.statusUpdate(order);
            return new Result(true,"修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"修改失败");
        }
    }

    @Override
    public void delete(Integer id) {
        orderDao.delete(id);
    }

    @Override
    public Result updateFile(Order order) {
        //判断该订单是否存在
        Order orderById = orderDao.findById(order.getId());
        if (orderById==null){
            //订单不存在
            return new Result(false,"结果上传失败，未查询到该订单，请刷新重试！");
        }
        //订单存在，判断订单状态是否为未开始
        if ("未开始".equals(orderById.getOrderStatus())){
            return new Result(false,"结果上传失败，请确认该订单是否已开始！");
        }
        try {
            //根据id将订单状态设置为已结束，并将文件地址存入数据库
            String orderStatus="已结束";
            order.setOrderStatus(orderStatus);
            orderDao.updateFile(order);
            return new Result(true,"结果上传成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"结果上传失败，请刷新重试");
        }
    }

    @Override
    public List<Order> findByPhoneNumber(String telephone) {
        List<Order> orderList=orderDao.findByPhoneNumber(telephone);
        for (Order order : orderList) {
            try {
                String orderDateString = DateUtils.parseDate2String(order.getOrderDate());
                order.setOrderDateString(orderDateString);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return orderList;
    }
}
